package com.hctforgreen.greenservice.ui.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.hctforgreen.greenservice.MainActivityV2;
import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.ctr.HctController;
import com.hctforgreen.greenservice.db.DBMessageManager;
import com.hctforgreen.greenservice.model.AssignLoginEntity;
import com.hctforgreen.greenservice.model.BookTypeListEntity.BookTypeEntity;
import com.hctforgreen.greenservice.model.DataVersionCodeEntity;
import com.hctforgreen.greenservice.model.LoginResultEntity;
import com.hctforgreen.greenservice.model.PersonPotinsEntity;
import com.hctforgreen.greenservice.ui.widget.PullToRefreshListView;
import com.hctforgreen.greenservice.ui.widget.PullToRefreshListView.OnRefreshListener;
import com.hctforgreen.greenservice.utils.DataVersionCodeUtil;
import com.hctforgreen.greenservice.utils.DownloadBookLstInitFinishUtil;
import com.hctforgreen.greenservice.utils.HctConstants;
import com.hctforgreen.greenservice.utils.HctResult;
import com.hctforgreen.greenservice.utils.LanguageSettingUtil;
import com.hctforgreen.greenservice.utils.LogUtil;
import com.hctforgreen.greenservice.utils.LoginResultStoreUtil;
import com.hctforgreen.greenservice.utils.MainFreshStoreUtil;
import com.hctforgreen.greenservice.utils.PersonPointsStoreUtil;
import com.hctforgreen.greenservice.utils.ScreenUtil;
import com.hctforgreen.greenservice.utils.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import ca.laplanete.mobile.pageddragdropgrid.OnPageChangedListener;
import ca.laplanete.mobile.pageddragdropgrid.PagedDragDropGrid;

public class MainV3ListAdapter extends BaseAdapter implements OnRefreshListener {

	private Activity mActivity;
	private PullToRefreshListView mListView;
	private View mConvertView;
	private MainActivityV2 mSelf;

	private MenuPagedDragDropGridAdapter menuAdapter;
	private PagedDragDropGrid dragDropGrid;
	
	private LinearLayout loadLyt;
	private LinearLayout reloadLyt;
	private Button reloadBtn;
	private TextView loadTv;
	/**
	 * 用于检测数据包版本是否需要更新，更新时是否显示大的进度条,false---不显示
	 */
	public boolean isProgressBarShow = false;
	/**
	 * 登录标识，用于判断登录掌上通正式服务器的次数，超过1次则判断为正式服务器宕机
	 */
	public int pingCount = 0;
	/**
	 * false为正式服务器，true为云服务器
	 */
	private boolean isCloudServer = false;
	
	public MainV3ListAdapter(Activity activity, PullToRefreshListView listView, MainActivityV2 self,
							 int pingCount, boolean whichServer) {
		mActivity = activity;
		mListView = listView;
		mSelf = self;
		mListView.setAdapter(this);
		mListView.setOnRefreshListener(this);
		this.pingCount = pingCount;
		this.isCloudServer = whichServer;
		/*if(!HctBackTestJsonController.isB_DEBUG()){
			Log.i("DATA", "传到MainV3ListAdapter的--pingCount   " + this.pingCount);
			Log.i("DATA", "传到MainV3ListAdapter的--isClounServer   " + this.isCloudServer);
		}*/
		
	}

	@Override
	public int getCount() {
		return 1;
	}

	@Override
	public Object getItem(int position) {
		return null;
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		LogUtil.e("MainV3ListAdapter", "getView");
		convertView = View.inflate(mActivity, R.layout.layout_main_v3, null);
		mConvertView = convertView;
		dealTopBannerParams(convertView);
		renderPersionNameTv(convertView);
		renderPersionPointsTv();
		getLoginPoints();

		assignLogin();
		

		//2016-4-25 390694改，，灾备环境下屏蔽机型、系列资料下载
		if (!isCloudServer) {//灾备环境下
			/**
			 * 1、初始化控件；
			 * 2、判断是否自动更新
			 */
			checkDataVersionCode();
		}

		/**
		 * 1、初始化控件；
		 */
		initWindow(convertView, false, null);
		return convertView;
	}

	/**
	 * 派工账号登录
	 */
	private void assignLogin() {
		String assignLogin = mActivity.getIntent().getStringExtra("assignLogin");
		if (TextUtils.isEmpty(assignLogin)) {
			return;
		}

		final LoginResultEntity loginEntity = LoginResultStoreUtil
				.get(mActivity);

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {
				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					hctResult = (HctResult) msg.obj;
					AssignLoginEntity entity = (AssignLoginEntity) hctResult.data;
					if (entity != null && "true".equals(entity.Result)) {// 拥有派工账号
						loginEntity.functions += ",!100!";
						LoginResultStoreUtil.save(mActivity, loginEntity);
						// View view = menuAdapter.getAssignView();
						// ImageView btnMenu = (ImageView) view
						// .findViewById(R.id.btn_main_menu);
						// btnMenu.setEnabled(true);
						// btnMenu.setClickable(true);
						menuAdapter.setAssignViewLogin(true);
					}
					break;

				case HctConstants.STATUS_FAILD:

					break;
				}
			}
		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);
					HctResult result = controller
							.assignLogin(loginEntity.phone);

					// HctResult hctResult = controller.assignLogin(phone);

					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}

				} catch (Exception e) {
					message.what = HctConstants.STATUS_FAILD;
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();

	}

	private void initTitleButtonBar(View convertView) {
		PagedDragDropGrid dragDropGrid = (PagedDragDropGrid) convertView.findViewById(R.id.gridview);
		this.dragDropGrid = dragDropGrid;
		menuAdapter = new MenuPagedDragDropGridAdapter(mSelf, dragDropGrid, pingCount, isCloudServer);
		dragDropGrid.setAdapter(menuAdapter);

		final RadioGroup radioGroup = (RadioGroup) convertView
				.findViewById(R.id.rg_page);
		if (menuAdapter.getPageSize() > 1) {
			Utils.showImgCount(radioGroup, menuAdapter.getPageSize(), mActivity);
		}
		dragDropGrid.setOnPageChangedListener(new OnPageChangedListener() {

			@Override
			public void onPageChanged(PagedDragDropGrid sender,
					int newPageNumber) {
				if (radioGroup.getChildCount() > 1) {
					try {
						((RadioButton) radioGroup.getChildAt(newPageNumber))
								.setChecked(true);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		});

		// /**
		// * 功能权限
		// */
		// final String functions = LoginResultStoreUtil.get(mSelf).functions;
		//
		// /**
		// * 开机密码
		// */
		// final Button mainTop1Btn = (Button) convertView
		// .findViewById(R.id.btn_main_top_1);
		// /**
		// * 条码扫描
		// */
		// final Button mainTop2Btn = (Button) convertView
		// .findViewById(R.id.btn_main_top_2);
		// /**
		// * 调试维修
		// */
		// final Button mainTop3Btn = (Button) convertView
		// .findViewById(R.id.btn_main_top_3);
		// /**
		// * 通知
		// */
		// final Button mainCenter1Btn = (Button) convertView
		// .findViewById(R.id.btn_main_center_1);
		// /**
		// * 技术资料
		// */
		// final Button mainCenter2Btn = (Button) convertView
		// .findViewById(R.id.btn_main_center_2);
		// /**
		// * 信息反馈
		// */
		// final Button mainCenter3Btn = (Button) convertView
		// .findViewById(R.id.btn_main_center_3);
		// /**
		// * 下载管理
		// */
		// final Button mainBottom1Btn = (Button) convertView
		// .findViewById(R.id.btn_main_bottom_1);
		// /**
		// * 软件设置
		// */
		// final Button mainBottom2Btn = (Button) convertView
		// .findViewById(R.id.btn_main_bottom_2);
		//
		// /**
		// * 视频播放
		// */
		// final Button mainBottom3Btn = (Button) convertView
		// .findViewById(R.id.btn_main_bottom_3);
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_STARTPWD)) {
		// mainTop1Btn.setEnabled(false);
		// } else {
		// mainTop1Btn.setEnabled(true);
		// }
		//
		// mainTop1Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// // if (functions == null
		// // || !functions
		// // .contains(LoginResultEntity.FUNCTION_STARTPWD)) {
		// // Toast.makeText(mSelf,
		// // mSelf.getString(R.string.function_power),
		// // Toast.LENGTH_LONG).show();
		// // return;
		// // }
		// MobclickAgent.onEvent(mActivity, "Account_start_pwd");
		// Intent intent = new Intent(mActivity, StartPwdActivity.class);
		// // 选择是否需要定位并传参给下一个界面定位（默认是）
		// intent.putExtra("loc", true);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// mActivity.startActivity(intent);
		//
		// }
		// });
		// // // 开机密码 英文版或系统语言为非中文时显示为不可点
		// // initStartPwdButton(mainTop1Btn);
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_CAPTURE)) {
		// mainTop2Btn.setEnabled(false);
		// } else {
		// mainTop2Btn.setEnabled(true);
		// }
		// mainTop2Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_barcode_scan");
		// Intent intent = new Intent(mActivity, CaptureActivity.class);
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// mActivity.startActivityForResult(intent, mSelf.ZXING_DATA);
		// }
		// });
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_DEBUG)) {
		// mainTop3Btn.setEnabled(false);
		// } else {
		// mainTop3Btn.setEnabled(true);
		// }
		//
		// mainTop3Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_debug_service");
		//
		// Intent intent = new Intent(mActivity, DebugActivity.class);
		// // 传递值（可能会用于区别直接进入调试还是通过扫码进入）
		// intent.putExtra("params", "");
		// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// mActivity.startActivity(intent);
		// }
		// });
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_MESSAGEFIRST)) {
		// mainCenter1Btn.setEnabled(false);
		// } else {
		// mainCenter1Btn.setEnabled(true);
		// }
		//
		// mainCenter1Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_notification");
		// Intent intent = new Intent();
		// intent.setClass(mActivity, MessageFirstActivityV2.class);
		// mActivity.startActivityForResult(intent,
		// mSelf.REQUEST_UPDATE_MSG);
		// }
		// });
		// if (functions == null
		// || !functions
		// .contains(LoginResultEntity.FUNCTION_TECHNICALDATA)) {
		// mainCenter2Btn.setEnabled(false);
		// } else {
		// mainCenter2Btn.setEnabled(true);
		// }
		//
		// mainCenter2Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_technical_data");
		// Intent intent = new Intent();
		// intent.setClass(mActivity, TechnicalDataActivityV4.class);
		// intent.putExtra(HctConstants.ON_ACTIVITY_KEY_MACHINE_ENTITY,
		// new MachineEntity());
		// mActivity.startActivity(intent);
		// }
		// });
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_FEEDBACK)) {
		// mainCenter3Btn.setEnabled(false);
		// } else {
		// mainCenter3Btn.setEnabled(true);
		// }
		// mainCenter3Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_feadback");
		// Intent intent = new Intent();
		// intent.setClass(mActivity, FeedbackActivity.class);
		// mActivity.startActivity(intent);
		// }
		// });
		//
		// if (functions == null
		// || !functions
		// .contains(LoginResultEntity.FUNCTION_DOWNLOADMANAGER)) {
		// mainBottom1Btn.setEnabled(false);
		// } else {
		// mainBottom1Btn.setEnabled(true);
		// }
		// mainBottom1Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_download_management");
		// Intent intent = new Intent();
		// intent.setClass(mActivity, DownloadManagerActivityV2.class);
		// mActivity.startActivity(intent);
		// }
		// });
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_SETTING)) {
		// mainBottom2Btn.setEnabled(false);
		// } else {
		// mainBottom2Btn.setEnabled(true);
		// }
		// mainBottom2Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// MobclickAgent.onEvent(mActivity, "Account_software_setting");
		// Intent intent = new Intent();
		// intent.setClass(mActivity, SettingActivity.class);
		// mActivity.startActivity(intent);
		// }
		// });
		//
		// if (functions == null
		// || !functions.contains(LoginResultEntity.FUNCTION_VIDEO)) {
		// mainBottom3Btn.setEnabled(false);
		// } else {
		// mainBottom3Btn.setEnabled(true);
		// }
		// // mainBottom3Btn.setVisibility(View.INVISIBLE);
		// mainBottom3Btn.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// Intent intent = new Intent();
		// intent.setClass(mActivity, VideoTypesActivity.class);
		// mActivity.startActivity(intent);
		// }
		// });
	}

	/**
	 * 多语言设置|系统语言设置 非中文版隐藏
	 */
	private void initStartPwdButton(final Button btn) {
		int languageType = LanguageSettingUtil.get(mActivity);
		if (languageType == 1) {// 英文版
			btn.setEnabled(false);
			return;
		}
		if (languageType == -1) {
			Locale locale = mActivity.getResources().getConfiguration().locale;
			String language = locale.getLanguage();
			if (!language.endsWith("zh")) {// 非中文版
				btn.setEnabled(false);
				return;
			}
		}

	}

	private void initView(View convertView){
		loadLyt = (LinearLayout) convertView
				.findViewById(R.id.lyt_default_load);
		reloadLyt = (LinearLayout) convertView
				.findViewById(R.id.lyt_default_reload);
		reloadBtn = (Button) convertView
				.findViewById(R.id.btn_default_reload);
		loadTv = (TextView) convertView
				.findViewById(R.id.tv_default_load);
	}
	/**
	 * 1、进入主页时，判断是否要自动更新版本，如果版本不一致则更新，版本一致则不自动更新；
	 * 2、初始化消息未读数，标题栏
	 * 3、下载基础资料
	 * @param convertView
	 * @param bTopRefresh 是否顶部刷新
	 * @param entity 版本号
	 */
	private void initWindow(View convertView, boolean bTopRefresh,
			DataVersionCodeEntity entity) {
		initView(convertView);
		/**
		 * 如果数据版本不一致，则刷新访问服务器
		 */		
		/*if (!isProgressBarShow) {
			//Log.i("hh", "initWindow");
			getAllSeries(convertView, bTopRefresh, entity);
		}	*/
		//getAllSeries(convertView, bTopRefresh, entity);
		//根据页码显示最下面的页码小圆点
		initTitleButtonBar(convertView);
		updateMsgCount(true, convertView);
	}

	/**
	 * 
	 * 更新消息未读数
	 */
	public void updateMsgCount(final boolean update) {
		updateMsgCount(update, mConvertView);
	}

	/**
	 * pageGirdView可能被回收，需要重新初始化
	 */
	public void initMenuAdapter() {
		initTitleButtonBar(mConvertView);
		updateMsgCount(true, mConvertView);
	}

	/**
	 * 获取登陆积分并显示
	 */
	private void getLoginPoints() {
		new Thread() {
			public void run() {

				HctController controller = new HctController(mActivity);
				try {
					final HctResult hctResult = controller
							.getLoginPoints(LoginResultStoreUtil.get(mActivity).personId);
					if (hctResult != null) {
						mActivity.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								PersonPotinsEntity entity = (PersonPotinsEntity) hctResult.data;
								if (entity != null && entity.addPoints != null
										&& entity.addPoints.trim().length() > 0) {
									try {
										Integer points = Integer
												.parseInt(entity.addPoints);
										if (points > 0) {

											Utils.showAddPointsToast(
													mActivity,
													points,
													mActivity
															.getString(R.string.add_point_oper_login));
										}
									} catch (NumberFormatException e) {
										e.printStackTrace();
									}
								}
								renderPersionPointsTv();
							}
						});
					}

				} catch (Exception e) {
					e.printStackTrace();
				}

			};
		}.start();

	}

	/**
	 * 
	 * 更新消息未读数
	 * 
	 * @param update
	 *            是否需要从服务器同步，首次点击进通知模块跟服务器同步，
	 *            获取最新通知消息存在本地数据库，往后进去不跟服务器同步获取通知，而是从本地数据库获取
	 */
	private void updateMsgCount(final boolean update, View convertView) {
		/**
		 * 功能权限
		 */
		final String functions = LoginResultStoreUtil.get(mSelf).functions;
		if (functions == null
				|| !functions.contains(LoginResultEntity.FUNCTION_MESSAGEFIRST)) {
			return;
		}

		if (menuAdapter == null || menuAdapter.getMsgView() == null) {
			return;
		}
		final TextView newMsgCountTv = (TextView) menuAdapter.getMsgView()
				.findViewById(R.id.tv_new_msg_count);

		final ImageView newMsgCountBgIv = (ImageView) menuAdapter.getMsgView()
				.findViewById(R.id.iv_new_msg_count);
		/**
		 * 未读通知条数获取
		 */
		new HandlerThread("get_count") {
			public void run() {
				try {
					if (update) {
						HctController controller = new HctController(mActivity);
						controller.getRecentMessages();
					}

					DBMessageManager dbMessageManager = new DBMessageManager(
							mActivity);
					final Integer count = dbMessageManager
							.getUnreadMessageCount();
					mActivity.runOnUiThread(new Runnable() {
						public void run() {

							if (count == null || count == 0) {
								newMsgCountTv.setVisibility(View.GONE);
								newMsgCountBgIv.setVisibility(View.GONE);
								menuAdapter.getMsgView()
										.findViewById(R.id.lyt_msg)
										.setVisibility(View.GONE);
							} else {
								newMsgCountTv.setText(count + "");
								newMsgCountTv.setVisibility(View.VISIBLE);
								newMsgCountBgIv.setVisibility(View.VISIBLE);
								menuAdapter.getMsgView()
										.findViewById(R.id.lyt_msg)
										.setVisibility(View.VISIBLE);
							}
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	private void renderPersionNameTv(View convertView) {
		if (convertView == null) {
			return;
		}
		final TextView persionNameTv = (TextView) convertView
				.findViewById(R.id.tv_persion_name);
		persionNameTv.setText(LoginResultStoreUtil.get(mActivity).personName);
	}

	/**
	 * 显示/刷新 积分信息
	 *
	 */
	public void renderPersionPointsTv() {
		if (mConvertView == null) {
			return;
		}

		final TextView pointsTv = (TextView) mConvertView
				.findViewById(R.id.tv_person_points);
		final TextView rankTv = (TextView) mConvertView
				.findViewById(R.id.tv_person_rank);
		final TextView ratingTv = (TextView) mConvertView
				.findViewById(R.id.tv_person_rating);
		pointsTv.setText(PersonPointsStoreUtil.get(mActivity).points);
		rankTv.setText(PersonPointsStoreUtil.get(mActivity).rank);
		ratingTv.setText(PersonPointsStoreUtil.get(mActivity).rating);
	}

	/**
	 * 1、所有系列信息
	 */
	private void getAllSeries(final View convertView,
			final boolean bTopRefresh, final DataVersionCodeEntity entity) {
		LogUtil.d("MainV3ListAdapter", "getAllSeries");
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
					LogUtil.i("hh", "刷新系列");
					//所有机型
					getAllMachines(convertView, bTopRefresh, entity);

					break;

				case HctConstants.STATUS_FAILD:
                    if (bTopRefresh) {
						reloadLyt.setVisibility(View.GONE);
					}else{
						reloadLyt.setVisibility(View.VISIBLE);
					}
					reloadBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							getAllSeries(convertView, bTopRefresh, entity);
						}
					});
					//取消顶部刷新
					if (bTopRefresh) {
						mListView.onRefreshComplete();
					}

					break;
				}
			}

		};

		loadTv.setVisibility(View.GONE);
		loadLyt.setVisibility(View.GONE);
		reloadLyt.setVisibility(View.GONE);


		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = null;
					result = controller.getAllSeries(bTopRefresh);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();

				}
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 2、所有机型信息
	 */
	private void getAllMachines(final View convertView,
			final boolean bTopRefresh, final DataVersionCodeEntity entity) {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
					LogUtil.i("hh", "刷新机型");
					//调试维修条目
					getAllColumns(convertView, bTopRefresh, entity);

					break;

				case HctConstants.STATUS_FAILD:
					if (bTopRefresh) {
						reloadLyt.setVisibility(View.GONE);
					}else{
						reloadLyt.setVisibility(View.VISIBLE);
					}
					loadLyt.setVisibility(View.GONE);	
					reloadBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							getAllMachines(convertView, bTopRefresh, entity);
						}
					});
					//取消顶部刷新
					if (bTopRefresh) {
						mListView.onRefreshComplete();
					}
					break;
				}
			}

		};	
		if (bTopRefresh) {
			if (isProgressBarShow){
				loadTv.setVisibility(View.VISIBLE);
				loadLyt.setVisibility(View.VISIBLE);
			}else{
				loadTv.setVisibility(View.GONE);
				loadLyt.setVisibility(View.GONE);
			}
		}else{
			loadTv.setVisibility(View.VISIBLE);
			loadLyt.setVisibility(View.VISIBLE);
		}
		reloadLyt.setVisibility(View.GONE);	
/*		loadTv.setVisibility(View.GONE);
		loadLyt.setVisibility(View.GONE);
		reloadLyt.setVisibility(View.GONE);*/
		
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller.getAllMachines(bTopRefresh);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();

				}
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 调试维修条目
	 * 
	 * @param convertView
	 * @param bTopRefresh
	 */
	private void getAllColumns(final View convertView,
			final boolean bTopRefresh, final DataVersionCodeEntity entity) {
		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);
					LogUtil.i("hh", "刷新调试维修条目");
					//Log.i("hh", "entity="+entity);
					if (entity!=null) {
						LogUtil.i("hh", "保存版本号");
						DataVersionCodeUtil.save(mActivity, entity.versionCode);
					}
					if (bTopRefresh) {
						/*//保存基础数据版本
						DataVersionCodeUtil.save(mActivity, entity.versionCode);*/
						mListView.onRefreshComplete();
						return;
					}

					if (DownloadBookLstInitFinishUtil.getInitFinished(mActivity)) {
						//onRefresh();
						//initTitleButtonBar(convertView);
						return;
					}
					/**
					 * 20160322--390694屏蔽
					 */
					/*getAllBooksWithAllChildSeriesAndDbSerieName(convertView,
							bTopRefresh, entity);*/
					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					//reloadLyt.setVisibility(View.VISIBLE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							getAllColumns(convertView, bTopRefresh, entity);
						}
					});
					if (bTopRefresh) {
						mListView.onRefreshComplete();
						return;
					}
					break;
				}
			}

		};
		/*loadTv.setVisibility(View.VISIBLE);
		loadLyt.setVisibility(View.VISIBLE);*/
		loadTv.setVisibility(View.GONE);
		loadLyt.setVisibility(View.GONE);
		reloadLyt.setVisibility(View.GONE);


		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller.getAllColumns(bTopRefresh);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();

				}
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 3、所有资料类别信息
	 */
	@Deprecated
	private void getAllBooktypes(final View convertView,
			final boolean bTopRefresh) {

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					hctResult = (HctResult) msg.obj;

					List<BookTypeEntity> dataList = (List<BookTypeEntity>) hctResult.data;

					break;

				case HctConstants.STATUS_FAILD:
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							getAllBooktypes(convertView, bTopRefresh);
						}
					});
					break;
				}
			}

		};

		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller.getAllBooktypes(bTopRefresh);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}
/**
 * 获取资料下面的子系列
 * 
 * 390694---20160322屏蔽
 */
	/*private void getAllBooksWithAllChildSeriesAndDbSerieName(
			final View convertView, final boolean bTopRefresh,
			final DataVersionCodeEntity entity) {

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:

					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.GONE);

					initTitleButtonBar(convertView);

					break;

				case HctConstants.STATUS_FAILD:
					
					loadLyt.setVisibility(View.GONE);
					reloadLyt.setVisibility(View.VISIBLE);
					reloadBtn.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {
							getAllBooksWithAllChildSeriesAndDbSerieName(
									convertView, bTopRefresh, entity);
						}
					});
					if (bTopRefresh) {
						mListView.onRefreshComplete();
						return;
					}
					break;
				}
				Intent intent = new Intent(mActivity, WifiUpdateService.class);
//				Intent intent = new Intent(WifiUpdateService.MY_NAME);
				mActivity.startService(intent);
			}

		};
		loadTv.setVisibility(View.VISIBLE);
		loadLyt.setVisibility(View.VISIBLE);
		reloadLyt.setVisibility(View.GONE);


		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller
							.getAllBooksWithAllChildSeriesAndDbSerieName(
									bTopRefresh, 0);
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();

				}
				handler.sendMessage(message);
			}
		}.start();
	}*/

	/**
	 * 按原图比例缩放顶部Banner
	 */
	private void dealTopBannerParams(View convertView) {
		ScreenUtil screenUtil = new ScreenUtil();
		int screenWidth = screenUtil.getScreenWidth(mActivity);
		int screenHeight = screenUtil.getScreenHeight(mActivity);
		int topBannerHeight = (screenWidth * 300 / 640);

		LinearLayout topBannerIv = (LinearLayout) convertView
				.findViewById(R.id.lyt_banner);
		FrameLayout bottomLyt = (FrameLayout) convertView
				.findViewById(R.id.lyt_main_bottom);

		LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,
				topBannerHeight);
		topBannerIv.setLayoutParams(params);

		params = new LayoutParams(LayoutParams.FILL_PARENT, screenHeight
				- topBannerHeight - Utils.dipToPx(25, mActivity));
		bottomLyt.setLayoutParams(params);
	}
/**
 * 顶部刷新时进行服务器APP版本与本地APP版本判断，如果数据包版本不是最新的则更新，反之提示
 */
	private void getDataVersionCode() {

		final Handler handler = new Handler() {
			public void handleMessage(Message msg) {

				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					// 当日首次刷新成功增加积分
					String shareDate = MainFreshStoreUtil.get(mActivity);
					final SimpleDateFormat dateFormat = new SimpleDateFormat(
							"yyyy-MM-dd");
					final String nowDate = dateFormat.format(new Date());
					if (!shareDate.equals(nowDate)) {// 当日首次刷新增加积分
						MainFreshStoreUtil.save(mActivity, nowDate);
						Utils.submitPoints(mActivity, 1, "", false);
					}

					hctResult = (HctResult) msg.obj;

					DataVersionCodeEntity entity = (DataVersionCodeEntity) hctResult.data;

					String localVersionCode = DataVersionCodeUtil
							.get(mActivity);

					if (!localVersionCode.equals(entity.versionCode)) {
						//mListView.onRefreshShow();
						//下拉刷新时，如果数据包版本不是是最新的则提示要更新
//						Log.i("DATA", "localVersionCode=="+localVersionCode);
//						Log.i("DATA", entity.versionCode);
//						initWindow(mConvertView, true, entity);
						
						initView(mConvertView);
						isProgressBarShow = false;
						getAllSeries(mConvertView, true, entity);
						initTitleButtonBar(mConvertView);
						updateMsgCount(true, mConvertView);
						
						//Intent intent = new Intent(mActivity, WifiUpdateService.class);
//						Intent intent = new Intent(WifiUpdateService.MY_NAME);	
						
						/**
						 * 20160323----390694屏蔽下拉时同时启动WiFi自动更新的服务
						 */
						//mActivity.startService(intent);
						return;
					}else{						
						/**下拉刷新时，如果数据包版本是最新的则提示无需更新
						 */						
					   dialogTips(R.string.dataversion_new);
					}

					mListView.onRefreshComplete();
					/*下拉时同时启动WiFi自动更新的服务
					 *20160323---390694移至判断版本是否一致的if判断里 
					 * Intent intent = new Intent(mActivity, WifiUpdateService.class);
//					Intent intent = new Intent(WifiUpdateService.MY_NAME);
					
					mActivity.startService(intent);*/
					break;

				case HctConstants.STATUS_FAILD:
						/**下拉刷新时，如果访问服务器失败则提示网络
						 */						
					dialogTips(R.string.net_error_hint);
					// Log.i("DATA", "1当前状态，done");
					mListView.onRefreshComplete();
					break;
				}
			}

		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mActivity);

					HctResult result = controller.getDataVersionCode();
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	/**
	 * 执行顶部刷新
	 */
	@Override
	public void onRefresh() {
		if (loadLyt == null || reloadLyt == null
				|| loadLyt.getVisibility() == View.VISIBLE
				|| reloadLyt.getVisibility() == View.VISIBLE) {
			mListView.onRefreshComplete();
			return;
		}
		//2016-4-25 390694改，，灾备环境下屏蔽机型、系列资料下载
		if (isCloudServer) {//灾备环境下
			dialogTips(R.string.disaster_recovery_could_not_download);
			mListView.onRefreshComplete();
			return;
		}else{
			getDataVersionCode();
		}
		
	}

	public PagedDragDropGrid getDragDropGrid() {
		return dragDropGrid;
	}

	public MenuPagedDragDropGridAdapter getMenuAdapter() {
		return menuAdapter;
	}
	
	/**
	 * 用于每次进入主页面时检测数据包版本是否需要更新
	 * @return
	 */
	private void checkDataVersionCode() {
		
		final Handler handler = new Handler() {
			
			public void handleMessage(Message msg) {
				
				HctResult hctResult = new HctResult();
				switch (msg.what) {
				case HctConstants.STATUS_SUCCESS:
					hctResult = (HctResult) msg.obj;

					DataVersionCodeEntity entity = (DataVersionCodeEntity) hctResult.data;

					String localVersionCode = DataVersionCodeUtil
							.get(mSelf);
					
					LogUtil.i("hh", "localVersionCode="+localVersionCode);
					LogUtil.i("hh", "entity.versionCode="+entity.versionCode);
					if (!localVersionCode.equals(entity.versionCode)) {
						isProgressBarShow = true;
						getAllSeries(mConvertView, true, entity);
					}else{
						isProgressBarShow = false;
					/*
					 * 20160324--390694屏蔽每次进入主页面如果是最新版本弹出的提示框
					 * dialogTips(R.string.dataversion_new);
					 * */
						
					}
					
					break;

				case HctConstants.STATUS_FAILD:
					isProgressBarShow = false;
					
					break;
				}
				
				
			}

		};

		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					HctController controller = new HctController(mSelf);

					HctResult result = controller.getDataVersionCode();
					if (result.status == HctConstants.STATUS_SUCCESS) {
						message.what = result.status;
						message.obj = result;
					} else {
						message.what = HctConstants.STATUS_FAILD;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				handler.sendMessage(message);
			}
		}.start();	
		
	}
	/**
	 * 对话框提示
	 * 390694
	 * @param tipsId
	 */
	public void dialogTips(int tipsId){
		try{
			Dialog dialog = null;
			AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
			builder.setTitle(R.string.dialog_default_title_hint)
					.setMessage(tipsId)
					.setPositiveButton(R.string.dialog_confirm_hint,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
								}
							});
			dialog = builder.create();
			dialog.show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
